package com.dounine.clouddisk360.parser;

import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dounine.clouddisk360.parser.deserializer.captcha.Captcha;
import com.dounine.clouddisk360.parser.deserializer.captcha.CaptchaConfig;
import com.dounine.clouddisk360.parser.deserializer.captcha.CaptchaConst;
import com.dounine.clouddisk360.parser.deserializer.captcha.CaptchaRequestInterceptor;
import com.dounine.clouddisk360.parser.deserializer.captcha.CaptchaResponseHandle;
import com.dounine.clouddisk360.pool.PoolingHttpClientConnection;

public class CaptchaParser extends BaseParser<CaptchaConfig> {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CaptchaParser.class);
	
	public static final String CHECK_NEED_CAPTCHA_URL = "http://login.360.cn/";

	@Override
	public void initConfig(CaptchaConfig captchaConfig) {
		super.initConfig(captchaConfig);//必需调用父类的initConfig方法,或者重写里面所定义的cookieStore路径
	}

	public Captcha parse(String account) {
		HttpGet request = initRequest(account);
		return execute(request);
	}
	
	public HttpGet initRequest(String account){
		try {
			URIBuilder uri = new URIBuilder(CHECK_NEED_CAPTCHA_URL);
			uri.addParameter(CaptchaConst.SRC_KEY, CaptchaConst.SRC_VAL);
			uri.addParameter(CaptchaConst.FROM_KEY, CaptchaConst.FROM_VAL);
			uri.addParameter(CaptchaConst.CHARSET_KEY, CaptchaConst.CHARSET_VAL);
			uri.addParameter(CaptchaConst.REQUESTSCEMA_KEY, CaptchaConst.REQUESTSCEMA_VAL);
			uri.addParameter(CaptchaConst.O_KEY, CaptchaConst.O_VAL);
			uri.addParameter(CaptchaConst.M_KEY, CaptchaConst.M_VAL);
			uri.addParameter(CaptchaConst.ACCOUNT_NAME, account);
			uri.addParameter(CaptchaConst.CAPTCHAAPP_KEY, CaptchaConst.CAPTCHAAPP_VAL);
			HttpGet request = new HttpGet(uri.build());
			return request;
		} catch (URISyntaxException e) {
			LOGGER.error("生成验证码请求对象失败");
		}
		return null;
	}

	public Captcha execute(HttpGet request) {
		super.httpClient = HttpClients.custom()
				.setConnectionManager(PoolingHttpClientConnection.getInstalce())
				.addInterceptorLast(new CaptchaRequestInterceptor())
				.setDefaultRequestConfig(cookieRequestConfig())
				.setDefaultCookieStore(super.httpClientContext.getCookieStore())
				.build();
			try {
				return super.httpClient.execute(request, new CaptchaResponseHandle(), super.httpClientContext);
			} catch (IOException e) {
				e.printStackTrace();
			}
		return null;
	}
	
	

}
